package com.chezai.client.activitys;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;

import com.chezai.client.R;
import com.chezai.client.adapter.TrainRecordAdapter;
import com.chezai.client.bean.ClassRecord;
import com.chezai.client.bean.CoachLoginRecord;
import com.chezai.client.bean.ImageInfo;
import com.chezai.client.bean.ReadIdCardBean;
import com.chezai.client.bean.Speech;
import com.chezai.client.bean.StudentStudyRecord;
import com.chezai.client.bean.TakePhotoEntity;
import com.chezai.client.bean.UserInfo;
import com.chezai.client.dao.manager.ClassRecordDaoManager;
import com.chezai.client.dao.manager.CoachLoginRecordDaoManager;
import com.chezai.client.dao.manager.StudentStudyRecordDaoManager;
import com.chezai.client.dao.manager.TerminalBaseInfoDaoManager;
import com.chezai.client.dao.manager.UserInfoDaoManager;
import com.chezai.client.global.Const;
import com.chezai.client.global.DeviceFactory;
import com.chezai.client.global.TerminalApplication;
import com.chezai.client.global.location.LocationMgr;
import com.chezai.client.server.TerminalSocketClientManager;
import com.chezai.client.server.util.TransmissionMessageUtil;
import com.chezai.client.utils.AppManager;
import com.chezai.client.utils.BuildDataUtil;
import com.chezai.client.utils.CameraMgr;
import com.chezai.client.utils.DateUtil;
import com.chezai.client.utils.DeviceUtils;
import com.chezai.client.utils.DialogUtils;
import com.chezai.client.utils.LocationUtils;
import com.chezai.client.utils.SpeechUtils;
import com.chezai.client.utils.TerminalUtils;
import com.chezai.client.utils.ThreadManager;
import com.chezai.client.utils.Util;
import com.chezai.client.widget.CountDownDialog;
import com.chezai.client.widget.LoginTypeDialog;
import com.chezai.client.widget.NormalAlertDialog;
import com.chezai.client.widget.QRDialog;
import com.chezai.client.widget.ReadCardDialog;
import com.jx.driving.request.Terminal0x0703Request;
import com.jx.driving.request.Terminal0x0900Request;
import com.jx.driving.response.AbstractResponse;
import com.jx.driving.response.Terminal0x8702Response;
import com.jx.driving.response.Terminal0x8703Response;
import com.jx.driving.transmission.Terminal0x0102Transmission;
import com.jx.driving.transmission.Terminal0x0201Transmission;
import com.jx.driving.transmission.Terminal0x0202Transmission;
import com.jx.driving.transmission.Terminal0x0305Transmission;
import com.jx.driving.transmission.Terminal0x0401Transmission;
import com.jx.driving.transmission.Terminal0x0402Transmission;
import com.jx.driving.transmission.Terminal0x8102Transmission;
import com.jx.driving.transmission.Terminal0x8201Transmission;
import com.jx.driving.transmission.Terminal0x8202Transmission;
import com.jx.driving.transmission.Terminal0x8401Transmission;
import com.jx.driving.transmission.Terminal0x8402Transmission;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 科目培训记录
 * <p>
 * Created by lky on 2017/9/13.
 */

public class OneAndFourActivity extends BaseActivity implements LoginTypeDialog.OnLoginTypeClickListener
        , ReadCardDialog.OnInputOverListener, QRDialog.OnCountDownTimerFinishListener
        , NormalAlertDialog.OnNormalAlertDialogListener, CountDownDialog.onCountDownDialogEventListener, DialogInterface.OnDismissListener {

    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    @BindView(R.id.tv_train_part)
    TextView tvTrainPart;
    private TrainRecordAdapter adapter;
    private long coachLoginRecordId;
    private int subject;
    private short loginType;
    private QRDialog qrDialog;
    private TransmissionMessageUtil messageUtil;
    private UserInfo mStudentInfo;
    private UserInfo mCoachInfo;
    private long classId;//学员课堂ID
    private long coachClassId;//教练课堂ID
    private BuildDataUtil buildDataUtil;
    private int mPhotoEventType;
    private int sequence;
    private boolean isStudentSignIn;
    private boolean isCoachSignOut = false;
    private String projectName;
    private StudentStudyRecord studentRecord;
    private long startTime;//开始时间
    private AlarmManager am;
    private PendingIntent sendIntent;
    private List<StudentStudyRecord> studentLoginRecodes;
    private boolean isHasUnFinishStuDialogShow;
    private boolean isCountDownFinish;
    private boolean isPrompt = false;//四小时倒计时是否已经提示过
    private TakePhotoEntity mTakePhoto;
    private boolean isReadingIdCard;

    public static void startOneAndFourActivity(Activity from, long coachLoginRecordId, int subject, String projectCode, String projectName) {
        if (AppManager.getAppManager().isOpenActivity(CameraActivity.class)) return;
        Intent intent = new Intent(from, OneAndFourActivity.class);
        intent.putExtra("coachLoginRecordId", coachLoginRecordId);
        intent.putExtra("subject", subject);
        intent.putExtra("projectCode", projectCode);
        intent.putExtra("projectName", projectName);
        from.startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
        DialogUtils.dismissDialog();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_train_record;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        LinearLayoutManager manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(manager);
        adapter = new TrainRecordAdapter(R.layout.item_train_record);
        recyclerView.setAdapter(adapter);
    }

    @Override
    public void initData() {
        messageUtil = new TransmissionMessageUtil();
        Intent intent = getIntent();
        coachLoginRecordId = intent.getLongExtra("coachLoginRecordId", 0);
        subject = intent.getIntExtra("subject", 0);
        String projectCode = intent.getStringExtra("projectCode");
        projectName = intent.getStringExtra("projectName");
        tvTrainPart.setText(subject == Const.TrainPart.ONE ? "第一部分" : "第四部分");
        CoachLoginRecord coachLoginRecord = CoachLoginRecordDaoManager.getInstance().findCoachLoginRecord(coachLoginRecordId);
        startTime = coachLoginRecord.getSignInTime();
        mCoachInfo = coachLoginRecord.getCoachInfo();
        coachClassId = BuildDataUtil.getCoachClassId();
        buildDataUtil = new BuildDataUtil();
        buildDataUtil.setPart(subject + "");
        buildDataUtil.setProject(projectCode);
        updateList();
        startAlarm();
    }


    private void updateList() {
        List<StudentStudyRecord> studentLoginRecordes = StudentStudyRecordDaoManager.getInstance().findStudentLoginRecordes(coachLoginRecordId);
        adapter.setNewData(studentLoginRecordes);
    }

    /**
     * 开启定时
     */
    @SuppressLint("ShortAlarm")
    private void startAlarm() {
        Intent intent = new Intent(Const.ALARM_ACTION);
        sendIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        am.cancel(sendIntent);
        am.setRepeating(AlarmManager.RTC_WAKEUP, startTime, 5 * 1000, sendIntent);
    }

    /**
     * 上课持续4小时 提示语音课程超时
     * 登出持续7小时，语音提示，并显示倒计时弹窗
     *
     * @param action 事件
     */
    @Subscribe
    public void onEventAlarmAction(String action) {
        if (TextUtils.equals(action, Const.ALARM_ACTION)) {
            long currentTime = System.currentTimeMillis();
            long hours = TimeUnit.MILLISECONDS.toHours(currentTime - startTime);
            if (hours >= 7) {
                try {
                    if (am != null) {
                        am.cancel(sendIntent);
                    }
                } catch (Exception e) {
                }
                SpeechUtils.getInstance().playOrComposed(Speech.CLASS_OUT_TIME_SEVEN_HOUR.getMsg(), Speech.CLASS_OUT_TIME_SEVEN_HOUR.getFilePath());
                showCountDownDialog();
            } else if (hours < 7 && hours >= 4 && !isPrompt) {
                isPrompt = true;
                SpeechUtils.getInstance().playOrComposed(Speech.CLASS_OUT_TIME_FOUR_HOUR.getMsg(), Speech.CLASS_OUT_TIME_FOUR_HOUR.getFilePath());
            }
        }
    }

    /**
     * 显示倒计时提示框
     * 29秒倒计时
     */
    private void showCountDownDialog() {
        CountDownDialog dialog = new CountDownDialog(this, 29);
        dialog.setOnCountDownDialogEventListener(this);
        dialog.show();
    }

    @Override
    public void onFinish(Dialog dialog) {
        try {
            dialog.dismiss();
        } catch (Exception e) {
            e.printStackTrace();
        }
        isCoachSignOut = true;
        isCountDownFinish = true;
        checkUnFinishStu();
    }

    @Override
    public void onCancel(Dialog dialog) {
        try {
            dialog.dismiss();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.btn_coach_signout, R.id.btn_student_signin, R.id.btn_student_signout, R.id.tv_train_part})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_coach_signout:
                isCoachSignOut = true;
                checkUnFinishStu();
                break;
            case R.id.btn_student_signin:
                isStudentSignIn = true;
                isCoachSignOut = false;
                showLoginType(true);
                break;
            case R.id.btn_student_signout:
                isStudentSignIn = false;
                isCoachSignOut = false;
                showLoginType(false);
                break;
            case R.id.tv_train_part:
                if (DeviceUtils.fastFiveClick()) {
                    Intent intent = new Intent(this, DebugActivity.class);
                    startActivity(intent);
                }
                break;
        }

    }

    /**
     * 检查是否有学员未登出
     */
    private void checkUnFinishStu() {
        studentLoginRecodes = StudentStudyRecordDaoManager.getInstance().findUnSignoutStudentLoginRecordes(coachLoginRecordId);
        if (studentLoginRecodes == null || studentLoginRecodes.size() == 0) {
            if (isCountDownFinish) {
                coachOrStudentSign(mCoachInfo.getIDCardNum());
            } else {
                showLoginType(false);
            }
        } else {
            if (!isHasUnFinishStuDialogShow && !isCountDownFinish) {
                DialogUtils.showDoubleButtonAlertDialog(this, "温馨提示"
                        , "当前有 " + studentLoginRecodes.size() + " 位学员未签退"
                        , "继续签退", "取消签退"
                        , Const.DIALOG_HAS_UNFINISH_TAG, this);
                isHasUnFinishStuDialogShow = true;
            } else {
                signOutStudent();
            }
        }
    }

    /**
     * 弹出登陆方式
     *
     * @param isSign true登录，false登出
     */
    public void showLoginType(boolean isSign) {
        int loginType = TerminalBaseInfoDaoManager.getInstance().getTerminalBaseInfo().getLoginType();
        byte[] bytes = Util.intToByte7(loginType);
        LoginTypeDialog dialog = new LoginTypeDialog(this);
        dialog.setLoginType(bytes);
        dialog.isSign(isSign);
        dialog.setOnLoginTypeClickListener(this);
        dialog.show();
    }

    @Override
    public void onLoginTypeClick(Dialog dialog, View v, short loginType) {
        dialog.dismiss();
        this.loginType = loginType;
        switch (loginType) {
            case Const.LOGIN_TYPE_FACE:
            case Const.LOGIN_TYPE_VERT:
            case Const.LOGIN_TYPE_WX:
                showToast("暂不支持");
                break;
            case Const.LOGIN_TYPE_IDCARD:
                isReadingIdCard = true;
                DialogUtils.showProgressBarDialog(this, "读卡中...", this);
                DeviceFactory.hardware.readIDCard(this);
                break;
            case Const.LOGIN_TYPE_APP:
                tell0x0401Tranmission(loginType, null);
                break;
            case Const.LOGIN_TYPE_RFID:
                String channelModel = TerminalApplication.channelModel;
                if (Const.QHYC_C103.equals(channelModel)) {
                    showReadCardDialog();
                } else {
                    String cardNumber = DeviceFactory.hardware.readIcCard(this);
                    tell0x0401Tranmission(loginType, cardNumber);
                }
                break;
        }
    }

    //小鹿设备外接刷卡
    public void showReadCardDialog() {
        ReadCardDialog readCardDialog = new ReadCardDialog(this);
        readCardDialog.setOnInputOverListener(this);
        readCardDialog.show();
    }

    @Override
    public void onInputOver(Dialog dialog, String result) {
        dialog.dismiss();
        tell0x0401Tranmission(Const.LOGIN_TYPE_RFID, result);
    }

    /**
     * 根据用户身份 发送0x0401 身份认证透传消息
     *
     * @param type       登录方式
     * @param cardNumber IC卡号
     */
    public void tell0x0401Tranmission(short type, String cardNumber) {
        Terminal0x0401Transmission ox0401 = new Terminal0x0401Transmission();
        ox0401.setType(type);
        ox0401.setUserType(isCoachSignOut ? Const.LOGIN_ROLE_COACH : Const.LOGIN_ROLE_STUDENT);
        if (Const.LOGIN_TYPE_RFID == type || Const.LOGIN_TYPE_IDCARD == type) {
            ox0401.setCardCode(cardNumber);
        }
        TransmissionMessageUtil messageUtil = new TransmissionMessageUtil();
        TerminalSocketClientManager.getInstance().tellWithNeedAuth(messageUtil.buildTerminal0x0900Request(ox0401, false, true));
    }

    /**
     * 读取身份证
     *
     * @param cardEntry
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventReadIDCard(ReadIdCardBean cardEntry) {
        DialogUtils.dismissDialog();
        if (ReadIdCardBean.STATUS_NO_CONNECT == cardEntry.status) {
            showToast("请检查设备连接是否成功");
        } else if (ReadIdCardBean.STATUS_ERROR == cardEntry.status) {
            showToast("未检测到身份证");
        } else if (ReadIdCardBean.STATUS_SUCESS == cardEntry.status) {
            isReadingIdCard = false;
            tell0x0401Tranmission(Const.LOGIN_TYPE_IDCARD, cardEntry.uid);
        }
    }

    /**
     * @param ox8401 身份认证
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent0x8401Transmission(Terminal0x8401Transmission ox8401) {
        //请求身份认证信息应答
        switch (ox8401.getResult()) {
            case 0:
                ox8401Sucess(ox8401);
                break;
            case 1:
                showToast("获取信息失败");
                break;
            case 9:
                showToast("其他错误");
                break;
        }
    }

    public void ox8401Sucess(Terminal0x8401Transmission ox8401) {
        switch (loginType) {
            case Const.LOGIN_TYPE_WX:
                break;
            case Const.LOGIN_TYPE_VERT:
                break;
            case Const.LOGIN_TYPE_FACE:
                break;
            case Const.LOGIN_TYPE_APP:
                qrDialog = DialogUtils.showQRDialog(this, new String(ox8401.getContent()), this);
                if (qrDialog == null) {
                    showToast("二维码获取失败，请重新获取！");
                }
                break;
            case Const.LOGIN_TYPE_IDCARD:
            case Const.LOGIN_TYPE_RFID:
                coachOrStudentSign(new String(ox8401.getContent()));
                break;

        }
    }

    /**
     * 扫码成功，APP端点开始教学 之后
     * 服务下发教练，学员信息，并获取统一编号
     *
     * @param ox8702 ox8702协议
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent0x8702Response(Terminal0x8702Response ox8702) {
        if (qrDialog != null && qrDialog.isShowing()) {
            qrDialog.dismiss();
        }
        coachOrStudentSign(ox8702.getCardCode());
    }

    private void coachOrStudentSign(String IDNumber) {
        if (isCoachSignOut) {
            if (TextUtils.equals(IDNumber, mCoachInfo.getIDCardNum())) {
                CameraActivity.startCameraActivity(this
                        , Const.TakePhotoMode.COUNT_DOWN_TIME
                        , 2, Const.PhotoEventType.TEACHE_SIGN_OUT
                        , subject, ""
                        , mCoachInfo.getName()
                        , Const.CameraChannel.FONT, null,null,false);
            } else {
                DialogUtils.showSingleButtonAlertDialog(this, "温馨提示"
                        , "登出教练与登录教练信息不符\n当前登录教练为：" + mCoachInfo.getName()
                        , "确定", NormalAlertDialog.Builder.DIALOG_STYLE_NORMAL
                        , Const.ALERT_COACH_DIFF_TAG, this);
            }
        } else {
            studentSignInOrSignOut(IDNumber);
        }
    }

    /**
     * 学员签到或签退
     *
     * @param IDNumber 身份证号
     */
    public void studentSignInOrSignOut(String IDNumber) {
        mStudentInfo = UserInfoDaoManager.getInstance().insertUserInfoOrFind(IDNumber);
        StudentStudyRecord studentRecord = StudentStudyRecordDaoManager.getInstance().findStudentLoginRecord(coachLoginRecordId, mStudentInfo.get_ID());
        if (isStudentSignIn) {//学员签到
            if (studentRecord != null && studentRecord.getSiginOutTime() == null) {
                showToast("已签到，请勿重复");
            } else {
                tell0x0402Transmission(IDNumber);
            }
        } else {//学员签退
            if (studentRecord == null) {
                showToast("请先签到");
            } else {
                classId = studentRecord.getClassRecord().getClassId();
                takeStudentSignOutPhoto();
            }
        }
    }

    /**
     * 学员登出拍照
     */
    private void takeStudentSignOutPhoto() {
        if (isCoachSignOut) {
            SpeechUtils.getInstance().playOrComposed("请" + mStudentInfo.getName() + "学员对准摄像头拍照", SpeechUtils.getVideoTempPath());
            CameraActivity.startCameraActivity(this
                    , Const.TakePhotoMode.COUNT_DOWN_TIME
                    , 2, Const.PhotoEventType.STUDENT_SIGN_OUT
                    , subject
                    , mStudentInfo.getName()
                    , mCoachInfo.getName()
                    , Const.CameraChannel.FONT, null,null,false);
        } else {
            CameraMgr.startFaceCamera(this,
                    mStudentInfo.getUnifiedNum(),
                    Const.PhotoEventType.STUDENT_SIGN_OUT,
                    subject,
                    mStudentInfo.getName(),
                    mCoachInfo.getName(),
                    null);
        }
    }

    /**
     * 根据用户身份 获取统一编号
     *
     * @param IDNumber 身份证号
     */
    private void tell0x0402Transmission(String IDNumber) {
        DialogUtils.showProgressBarDialog(this, R.string.get_unified_num);
        Terminal0x0402Transmission ox0402 = new Terminal0x0402Transmission();
        ox0402.setType((short) 6);
        ox0402.setNo(IDNumber);
        TerminalSocketClientManager.getInstance().tellWithNeedAuth(messageUtil.buildTerminal0x0900Request(ox0402, false, true));
    }

    @Override
    public void onCountDownTimerFinish(CountDownTimer countDownTimer) {
        tell0x0401Tranmission(Const.LOGIN_TYPE_APP, null);
    }

    /**
     * 学员统一编号信息应答
     *
     * @param ox8402 返回统一编号 0x0402
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent0x8402Transmission(Terminal0x8402Transmission ox8402) {
        short result = ox8402.getResult();
        //0：成功；1：失败（失败时无后续字段）；9：其他错误
        switch (result) {
            case 0:
                DialogUtils.showProgressBarDialog(this, R.string.get_user_info);
                String no = ox8402.getNo();//统一编号
                mStudentInfo.setUnifiedNum(no);
                mStudentInfo.setUserType(UserInfo.USER_STUDENT);
                UserInfoDaoManager.getInstance().update(mStudentInfo);
                Terminal0x0703Request ox0703 = new Terminal0x0703Request();
                ox0703.setUserType(Const.LOGIN_ROLE_STUDENT);
                ox0703.setUnifiedNum(no);
                TerminalSocketClientManager.getInstance().tellWithNeedAuth(ox0703);
                break;
            case 1:
                DialogUtils.dismissDialog();
                showToast("学员没有统一编号信息");
                break;
            case 9:
                DialogUtils.dismissDialog();
                showToast("其他错误");
                break;
        }
    }

    /**
     * 获取学员信息
     * 展示右侧项目内容
     *
     * @param ox8703 ox8703协议
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent0x8703Response(Terminal0x8703Response ox8703) {
        switch (ox8703.getResult()) {
            case 0:
                mStudentInfo.setName(TextUtils.isEmpty(ox8703.getName()) ? "" : ox8703.getName());
                mStudentInfo.setSex(ox8703.getSex());
                mStudentInfo.setPhone(ox8703.getPhone());
                mStudentInfo.setPhotoUrl(ox8703.getPhotoUrl());
                mStudentInfo.setDrivingType(ox8703.getDrivingType());
                UserInfoDaoManager.getInstance().update(mStudentInfo);
                takeStudentSignInPhoto();
                break;
            case 1:
                showToast("未找到学员信息");
                break;
        }
    }

    /**
     * 上报学员登录
     */
    public void tell0x0201Transmission() {
        classId = Long.parseLong(DateUtil.timestampStr(DateUtil.sf20));
        DialogUtils.showProgressBarDialog(this, R.string.sign_in);
        buildDataUtil.setStudentDrivingType(mStudentInfo.getDrivingType());
        String courseId = buildDataUtil.buildCourseId();
        //上报学员登陆
        Terminal0x0201Transmission ox0201 = new Terminal0x0201Transmission();
        ox0201.setUserNo(mStudentInfo.getUnifiedNum());
        ox0201.setCoachNo(mCoachInfo.getUnifiedNum());
        ox0201.setClassId(classId);
        ox0201.setCourse(courseId);
        ox0201.setGnss(LocationUtils.getGnssPackage(LocationMgr.getBestLocation()));
        TerminalSocketClientManager.getInstance().tellWithNeedAuth(messageUtil.buildTerminal0x0900Request(ox0201, false, true));
    }

    /**
     * 上报学员登录响应
     *
     * @param ox8201 协议
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent0x8201Transmission(Terminal0x8201Transmission ox8201) {
        //学员登录应答
        short result = ox8201.getResult();
        //登录结果1：登录成功；2：无效的学员编号；3：禁止登录的学员；4：区域外教学提醒；5：准教车型与培训车型不符；9：其他错误
        switch (result) {
            case 1:
                if (mTakePhoto != null) {
                    uploadPhoto(mTakePhoto);
                }
                break;
            case 2:
                showToast("无效的学员编号");
                break;
            case 3:
                showToast("禁止登录的学员");
                break;
            case 4:
                showToast("区域外教学提醒");
                break;
            case 5:
                showToast("准教车型与培训车型不符");
                break;
            case 9:
                //上次学员没有成功退出
                showToast("其他错误");
                break;
        }
    }

    //学员登录签到照片
    private void takeStudentSignInPhoto() {
        CameraMgr.startFaceCamera(this,
                mStudentInfo.getUnifiedNum(),
                Const.PhotoEventType.STUDENT_SIGN_IN,
                subject,
                mStudentInfo.getName(),
                mCoachInfo.getName(),
                null);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventTakePhoto(TakePhotoEntity takePhoto) {
        EventBus.getDefault().removeStickyEvent(takePhoto);
        if (TakePhotoEntity.TAKE_PHOTO_SUCESS == takePhoto.status) {
            if (Const.PhotoEventType.STUDENT_SIGN_IN == takePhoto.photoEventType) {
                this.mTakePhoto = takePhoto;
                tell0x0201Transmission();
            } else {
                uploadPhoto(takePhoto);
            }
        } else {
            showSingleAlertDialog("拍照失败请重试！", 3);
        }
    }

    private void uploadPhoto(TakePhotoEntity takePhoto) {
        DialogUtils.showProgressBarDialog(this, R.string.upload_image);
        mPhotoEventType = takePhoto.photoEventType;
        final ImageInfo imageInfo = TerminalUtils.getImageInfo(takePhoto.photoPath);
        //照片初始化
        Terminal0x0305Transmission transmission = getTerminal0x0305Transmission(imageInfo.imageNo, imageInfo.imageBuffer);
        Terminal0x0900Request req = new TransmissionMessageUtil().buildTerminal0x0900Request(transmission, false, false);
        TerminalSocketClientManager.getInstance().tellWithNeedAuth(req);
        ThreadManager.getInstance().getUploadPool().execute(new Runnable() {
            @Override
            public void run() {
                Integer result = TerminalUtils.sendToServer(imageInfo.imageBuffer, imageInfo.imageNo);
                sequence = result == null ? -1 : result;
            }
        });
    }


    /**
     * 初始化照片信息
     */
    private Terminal0x0305Transmission getTerminal0x0305Transmission(String imageNo, byte[] buffer) {
        Terminal0x0305Transmission transmission = new Terminal0x0305Transmission();
        transmission.setImageNo(imageNo);
        //1：平台拍照指令后上传自动请求上传；2：平台查询后要求上传；129：终端主动拍照上传；255：停止拍摄并上传图片
        transmission.setUploadType(Const.UploadPhotoType.TERMINAL_UPLOAD);
        if (mPhotoEventType == Const.PhotoEventType.STUDENT_SIGN_IN
                || mPhotoEventType == Const.PhotoEventType.STUDENT_SIGN_OUT) {
            transmission.setClassId(classId);
            transmission.setUserNo(mStudentInfo.getUnifiedNum());
        } else if (mPhotoEventType == Const.PhotoEventType.TEACHE_SIGN_OUT) {
            transmission.setUserNo(mCoachInfo.getUnifiedNum());
            transmission.setClassId(coachClassId);
        }
        transmission.setCameraChannel((short) 0);
        transmission.setSize((short) 2);
        transmission.setEventType((short) mPhotoEventType);
        transmission.setDataLength(buffer.length);
        transmission.setGnss(LocationUtils.getGnssPackage(LocationMgr.getBestLocation()));
        transmission.setTrustable((short) 100);
        int packageCount = TerminalUtils.getImagePackageCount(buffer);
        transmission.setPackageCount(packageCount);
        transmission.setAttachementList(TerminalApplication.getTerminalContext().getLocationAttachement());
        return transmission;
    }

    /**
     * 上传照片
     * 照片上传成功，进入相关界面
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventUploadImage(AbstractResponse response) {
        int msgId = response.getId();
        if (msgId == 0x900) {
            if (response.getResult() == 0) {
                Logger.t("UploadImage").d("sequence :" + response.getSequence() + "__result:" + response.getResult());
                if (response.getSequence() == sequence) {
                    DialogUtils.dismissDialog();
                    if (mPhotoEventType == Const.PhotoEventType.TEACHE_SIGN_OUT) {
                        tell0x0102Transmission(mCoachInfo.getUnifiedNum());
                    } else if (mPhotoEventType == Const.PhotoEventType.STUDENT_SIGN_OUT) {
                        tell0x0202Transmission();
                    } else if (mPhotoEventType == Const.PhotoEventType.STUDENT_SIGN_IN) {
                        saveData();
                    }
                }
            } else {
                DialogUtils.dismissDialog();
                showSingleAlertDialog("照片上传失败，请重试！", 3);
            }
        }
    }

    //提示
    public void showSingleAlertDialog(String content, int tag) {
        DialogUtils.showSingleButtonAlertDialog(this, "提示", content, "确定", NormalAlertDialog.Builder.DIALOG_STYLE_NORMAL, tag, this);
    }

    @Override
    public void onNormalAlertDialogClick(NormalAlertDialog dialog, View view, int btnType) {
        dialog.dismiss();
        if (dialog.getTag() == Const.DIALOG_HAS_UNFINISH_TAG) {
            if (btnType == NormalAlertDialog.NORMAL_ALERT_DIALOG_LEFT) {
                signOutStudent();
            } else {
                isHasUnFinishStuDialogShow = false;
            }
        }
    }

    private void signOutStudent() {
        studentLoginRecodes = StudentStudyRecordDaoManager.getInstance().findUnSignoutStudentLoginRecordes(coachLoginRecordId);
        StudentStudyRecord studyRecord = studentLoginRecodes.get(0);
        classId = studyRecord.getClassRecord().getClassId();
        mStudentInfo = studyRecord.getStuInfo();
        takeStudentSignOutPhoto();
    }

    /**
     * 学员上报签到，拍照上传成功之后
     * 保存课堂数据
     */
    public void saveData() {
        if (mStudentInfo != null) {
            buildDataUtil.setStudentDrivingType(mStudentInfo.getDrivingType());
            String courseNum = buildDataUtil.buildCourseId();
            ClassRecord classRecord = new ClassRecord();
            classRecord.setClassId(classId);
            classRecord.setCourseNum(courseNum);
            classRecord.setSid(mStudentInfo.get_ID());
            classRecord.setTrainPart(subject);
            classRecord.setTrainSubject(projectName);
            long classRecordId = ClassRecordDaoManager.getInstance().insertClassRecord(classRecord);
            StudentStudyRecordDaoManager.getInstance().insertStudentStudyRecord(coachLoginRecordId, mStudentInfo.get_ID(), classRecordId);
            mStudentInfo = null;
            classId = 0;
        }
        updateList();
    }

    //学员签退
    public void tell0x0202Transmission() {
        DialogUtils.showProgressBarDialog(this, R.string.sign_out);
        studentRecord = StudentStudyRecordDaoManager.getInstance().findStudentLoginRecord(coachLoginRecordId, mStudentInfo.get_ID());
        Terminal0x0202Transmission ox0202 = new Terminal0x0202Transmission();
        ox0202.setUserNo(mStudentInfo.getUnifiedNum());
        ox0202.setTime(DateUtil.timestampStr(DateUtil.sf19));
        ox0202.setClassId(classId);
        ox0202.setTotalTime((int) Math.abs(System.currentTimeMillis() - studentRecord.getSiginInTime() / 1000));
        ox0202.setTotalMileage(0);
        ox0202.setGnssPackage(LocationUtils.getGnssPackage(LocationMgr.getBestLocation()));
        TerminalSocketClientManager.getInstance().tellWithNeedAuth(messageUtil.buildTerminal0x0900Request(ox0202, false, true));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent0x8202Transmission(Terminal0x8202Transmission ox8202) {
        DialogUtils.dismissDialog();
        int result = ox8202.getResult();
        switch (result) {
            case 1:
                StudentStudyRecord studyRecord = StudentStudyRecordDaoManager.getInstance().updateStudentSignOutTime(studentRecord.get_ID());
                ClassRecordDaoManager.getInstance().updateClassRecordSignStatus(studentRecord.getClassRecordId(), ClassRecord.SIGN_OUT);
                long[] resultArr = DateUtil.getTimeDifference(studyRecord.getSiginInTime(), studyRecord.getSiginOutTime());
                SpeechUtils.getInstance().playOrComposed("本次培训时长为" + resultArr[0] + "分" + resultArr[1] + "秒,具体有效时长请在学车APP上查看", SpeechUtils.getVideoTempPath());
                updateList();
                if (isCoachSignOut) {
                    checkUnFinishStu();
                }
                studentRecord = null;
                showToast("学员签退成功");
                break;
            case 2:
                showToast("学员签退失败");
                break;
            case 9:
                showToast("其他错误");
                break;
        }
    }

    /**
     * 教练登出请求
     *
     * @param coachUnifiedNum 教练统一编号
     */
    public void tell0x0102Transmission(String coachUnifiedNum) {
        DialogUtils.showProgressBarDialog(this, R.string.sign_out);
        Terminal0x0102Transmission ox0102 = new Terminal0x0102Transmission();
        ox0102.setCoachNo(coachUnifiedNum);
        ox0102.setGnss(LocationUtils.getGnssPackage(LocationMgr.getBestLocation()));
        TerminalSocketClientManager.getInstance().tellWithNeedAuth(messageUtil.buildTerminal0x0900Request(ox0102, false, true));
    }

    /**
     * 教练登出应答
     *
     * @param ox8102 ox8102协议
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent0x8102Transmission(Terminal0x8102Transmission ox8102) {
        DialogUtils.dismissDialog();
        short result = ox8102.getResult();
        switch (result) {
            case 1://登出成功
                try {
                    am.cancel(sendIntent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                BuildDataUtil.clearCoachClassId();
                CoachLoginRecordDaoManager.getInstance().updateCoachSignoutTime(coachLoginRecordId);
                LoginActivity.openLogin(this, null, null);
                break;
            case 2://登出失败
                showToast("登出失败请重试");
                break;
            case 9://其他错误
                showToast("其他错误");
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        super.onKeyDown(keyCode, event);
        return true;
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        if (isReadingIdCard) {
            isReadingIdCard = false;
            DeviceFactory.hardware.closeSerialPort();
        }
    }
}
